package com.liu.frame.utils;
import android.util.Log;


import com.liu.frame.application.MyApplication;
import com.liu.frame.config.Constant;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

/**
 * V2.0
 * baibai
 */
public class TokenUtils {

    /**
     * 获得不需要登陆的token
     */
    public static String getLoginNotNeedToken(HashMap<String, String> map, String qType) {
        String tokenValue = "";
        String key = "";
        String key1 = "";
        String userid = "0";
        String string = "";
        String mConstant = "BAOBAOQIANBAO";
        string = getRandomCapitalLetter();
        // key1 = md5(mConstant + string)
        key1 = MD5Util.get32MD5Str(mConstant + "_" + string);
        //将私有参数和key1添加到map中
        Map<String, Object> mDefaultMaps = buildDefaultMaps(qType);
        mDefaultMaps.put("token", key1);
        mDefaultMaps.putAll(map);
        //将map排序且拼接keyvalue成string
        String gsonString = StringUtils.splicingMap(descByKey(mDefaultMaps));
//		LogUtils.e("Map拼接成字符串:" + gsonString);
        //MD5加密
        key = MD5Util.get32MD5Str(gsonString);
        tokenValue = key + "_" + userid + "_" + string;
        LogUtils.e("Token:"+tokenValue);
        return tokenValue;
    }

    /**
     * 获取随机的十位大写字母
     */
    private static String getRandomCapitalLetter() {
        Random rand = new Random();
        final int A = 'A', z = 'Z';
        StringBuilder sb = new StringBuilder();
        while (sb.length() < 10) {
            int number = rand.nextInt(z + 1);
            if (number >= A) {
                sb.append((char) number);
            }
        }
        return sb.toString();
    }

    /**
     * 存放appType、appVersion、Token键值
     **/
    private static Map<String, Object> buildDefaultMaps(String qType) {
        Map<String, Object> mDefaultMaps = new HashMap<>();
        mDefaultMaps.put("appType", Constant.appType);
        mDefaultMaps.put("appVersion", MyApplication.getInstance().appVersion);
        mDefaultMaps.put("qType", qType);
        mDefaultMaps.put("serviceVersion",Constant.serviceVersion);
        return mDefaultMaps;
    }

//    private static Map<String, Object> buildTokenMaps(Map<String, Object> mDefaultMaps, String token) {
//        mDefaultMaps.put("token", token);
//        for (String key : map.keySet()) {
//            mDefaultMaps.put(key, map.get(key));
//        }
//        return mDefaultMaps;
//    }


    /**
     * 得到需要传递登陆的token @param userid
     * 登录成功后返回的
     * parameter map //未加密的私有参数map
     */
    public static String getLoginNeedToken(HashMap<String, String> map, String ... parameters) {
        Map<String, Object> mDefaultMaps = buildDefaultMaps(parameters[0]);
        mDefaultMaps.putAll(map);
        // 默认值
        String unixTime = parameters[1];
        String Token = parameters[2];
        String userid =parameters[3];
        if (unixTime.isEmpty()&&Token.isEmpty()&&userid.isEmpty()){
            return  null;
        }
//        String Token = YidaiApplication.getInstance().getUserToken();
//        String userid = YidaiApplication.getInstance().getUserId();

        // 将userToken加入map
        String userToken = MD5Util.get32MD5Str(Token + "_" + unixTime);
        mDefaultMaps.put("token", userToken);

        //将map值进行排序;将降序后的map的key 和 value 拼接成字符串
        String gsonString = StringUtils.splicingMap(descByKey(mDefaultMaps));
//		LogUtils.e("Map拼接成字符串:" + gsonString);

        //MD5加密
        String key = MD5Util.get32MD5Str(gsonString);
        // 拼接返回值
        Log.e("key",key);
        Log.e("userId",userid);
        Log.e("unixTime",unixTime);
        return key + "_" + userid + "_" + unixTime;
    }

    /**
     * 获得拼接参数
     */
    public static String getParam(String token) {
        String par = "";
        Map<String, Object> map = new HashMap<>();
        map.put("appType", Constant.appType);
        map.put("appVersion", MyApplication.getInstance().appVersion);
        map.put("qType", Constant.qTypeApi);
        map.put("token", token);
        String str = descByKey(map).toString();
        par = str.substring(1, str.length() - 1).replaceAll(",", ";").replaceAll(" ", "");//去掉第一行和最后一行，将‘,’换成‘；’，将空格去掉
        return par;
    }

    /**
     * 按key进行降序排序
     *
     * @param map
     * @return
     */
    private synchronized static Map<String, Object> descByKey(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, Object> sortMap = new TreeMap<String, Object>(
                new Comparator<String>() {
                    public int compare(String str1, String str2) {
                        // 降序排序
                        return str1.compareTo(str2);
                    }
                });
        sortMap.putAll(map);
        return sortMap;
    }

}
